package chen.web.util;

import java.io.IOException;
import java.text.DateFormat;
import java.text.DateFormatSymbols;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class AllInOne
 */
public class AllInOne extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final String Path_Prefix = "/static/";
	private static final String Js_File_Suffix = ".js";
	private static final String Css_File_Suffix = ".css";
	private static final String Seperator = "___";
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AllInOne() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		if(request.getHeader("If-Modified-Since") == null){
			response.setHeader("Last-Modified", toGMTString(new Date()));
		} else {
			response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
			return;
		}
		
		//确定文件类型后缀
		String suffix = null;
		String fileNames = request.getParameter("js");
		if(fileNames != null){
			suffix = Js_File_Suffix;
			response.setContentType("text/javascript");
		} else {
			fileNames = request.getParameter("css");
			if(fileNames != null){
				suffix = Css_File_Suffix;
				response.setContentType("text/css");
			} else {
				return;
			}
		}
		
		String[] names = fileNames.split(Seperator);
		for(String name : names){
			include(request, response, name, suffix);
		}
	}
	
	private void include(HttpServletRequest request, HttpServletResponse response, String fileName, String suffix) throws ServletException, IOException{
		StringBuffer buffer = new StringBuffer();
		buffer.append(Path_Prefix).append(fileName).append(suffix);
		request.getRequestDispatcher(buffer.toString()).include(request, response);
	}

	private String toGMTString(Date date){
		DateFormat format = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss z", new DateFormatSymbols(Locale.US));
		format.setTimeZone(TimeZone.getTimeZone("GMT"));  
		return format.format(date);
	}

}
